import os, re, logging, json, sys
from .stat import run_stat
from .plot import run_plot
from .word import run_word

logger = logging.getLogger('NextApp-ONT-QC')


def __get_cell_info_list(cell_list_File):
    cell_stat_list = list()
    fp = open(cell_list_File)
    for line in fp:
        line = line.strip()
        if not line: continue
        cell_name = os.path.basename(line.rstrip('/'))
        stat_json_file = None
        for dir1 in os.listdir(line):
            for dir2 in os.listdir(os.path.join(line, dir1)):
                if dir2 == 'qc_report':
                    stat_json_file = os.path.join(line, dir1, dir2, 'qc_stat.json')
                    break
        if not stat_json_file or not os.path.exists(stat_json_file):
            logger.error('找不到统计json文件：%s' % line)
            sys.exit()
        cell_stat_list.append({'cell': cell_name, 'stat': json.loads(open(stat_json_file).read())})
    return cell_stat_list


def run_report(input, outdir, project, sample, writer, verifier):
    cell_info_list = __get_cell_info_list(input)
    volume_stat, distribution_stat = run_stat(cell_info_list)
    dcp_images, dip_images, dic_images, volume_image = run_plot(volume_stat, distribution_stat, outdir)
    run_word(project, sample, writer, verifier, outdir, volume_stat, dcp_images, dip_images, dic_images, volume_image)
